package com.loyal.loyalerp.humenresource.askleave.controller;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletConfigAware;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.loyal.loyalerp.commons.ServerResponse;
import com.loyal.loyalerp.humenresource.askleave.model.AskLeave;
import com.loyal.loyalerp.humenresource.askleave.model.vo.Check;
import com.loyal.loyalerp.humenresource.askleave.model.vo.GridVO;
import com.loyal.loyalerp.humenresource.askleave.service.AskLeaveService;
import com.loyal.loyalerp.humenresource.categoryDetail.service.CategoryDetailReadService;
import com.loyal.loyalerp.humenresource.employee.mapper.Gy_PersonMapper;
import com.loyal.loyalerp.humenresource.employee.service.Gy_PersonReadService;
import com.loyal.loyalerp.service.EmployeeService;
import com.loyal.loyalerp.service.impl.KaoQinServiceImpl;
import com.loyal.loyalerp.utils.PropertiesUtil;
import com.loyal.loyalerp.utils.ValidateUtil;

@Controller
@RequestMapping("/askleave")
public class AskLeaveController implements ServletContextAware, ServletConfigAware, Servlet, ServletConfig {
    
	@Autowired
	private KaoQinServiceImpl kaoqinService;
	
	@Value(value="${username1}")
	private String username;

	@Autowired
	private AskLeaveService askLeaveService;

	@Autowired
	private CategoryDetailReadService detailReadService;

	@Autowired
	private Gy_PersonReadService readService;

	@Autowired
	private EmployeeService userService;

	@Autowired
	private Gy_PersonMapper personMapper;
	private final String PERMISSION = "rs_qingjiaapply";
	private boolean DEBUGMODE = false;

	@RequestMapping("/jsp")
	public String listjsp(HttpServletRequest request) {
		if (!ValidateUtil.validateQuery(PERMISSION)) {
			return "basedata/askleave/403";
		}

		return "basedata/askleave/listAskLeave";
	}

	@RequestMapping("/jspcheck")
	public String listjspcheck(HttpServletRequest request) {
		if (!ValidateUtil.validateCheck(PERMISSION)) {
			return "basedata/askleave/403";
		}
		request.setAttribute("User", userService.getAllEmploy());
		return "basedata/askleave/listCheckAskLeave";
	}

	@ResponseBody
	@RequestMapping("/list")
	public Object list(Integer page, Integer rows)
			throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		if (!DEBUGMODE && !ValidateUtil.validateQuery(PERMISSION)) {
			return GridVO.fromPageInfo(askLeaveService.listCurrentUser(0, 0, 0));
		} else if (ValidateUtil.validateInput(PERMISSION)) {
			return GridVO.fromPageInfo(askLeaveService.listCurrentUserInput(0, 0));
		}
		Integer id = ValidateUtil.validateUser().getId();
		PageInfo<AskLeave> pageInfo = askLeaveService.listCurrentUser(id, page, rows);
		return GridVO.fromPageInfo(pageInfo);
	}

	@ResponseBody
	@RequestMapping("/listcheck")
	public Object listCheck(Integer page, Integer rows, Boolean isCheck, @RequestParam(required = false) String sTime,
			@RequestParam(required = false) String eTime, String personId)
			throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
		if (!DEBUGMODE && !ValidateUtil.validateQuery(PERMISSION)) {
			return GridVO.fromPageInfo(askLeaveService.listCurrentUser(0, 0, 0));
		}
		if (!DEBUGMODE && !ValidateUtil.validateCheck(PERMISSION)) {
			return GridVO.fromPageInfo(askLeaveService.listCurrentUser(0, 0, 0));
		}
		PageInfo<AskLeave> pageInfo;
		if (isCheck != null && isCheck) {
			pageInfo = askLeaveService.listAllCheckAndTime(page, rows, sTime, eTime, personId);
		} else {
			pageInfo = askLeaveService.listAllNotCheckAndTime(page, rows, sTime, eTime, personId);
		}
		Object obj = GridVO.fromPageInfo(pageInfo);
		return obj;
	}

/*	@ResponseBody
	@RequestMapping("/del")
	public Object del(HttpServletRequest request, Integer id, String picture, HttpServletResponse response) {
		if (picture != null && !picture.isEmpty()) {
			// RYWJSC
			String pathRoot = "";
			try {
				pathRoot = request.getSession().getServletContext().getRealPath("");
				if (picture.startsWith("/resources")) {
					new File(pathRoot + "/" + picture).delete();
				} else {
					new File(picture).delete();
				}
			} catch (Exception e) {
				return ServerResponse.createByError("删除失败，请确定目录文件是否存在 " + pathRoot + "/" + picture);
			}
		}
		if (!DEBUGMODE && !ValidateUtil.validateDel(PERMISSION)) {
			return ServerResponse.createByError("没有权限删除数据");
		}
		if (askLeaveService.hasCheck(id)) {
			return ServerResponse.createByError("已经审核过，无法再次修改");
		}
		askLeaveService.delAskLeave(id);
		return ServerResponse.createBySuccess();
	}*/
	
	
	@ResponseBody
	@RequestMapping("/del")
	public Object del(HttpServletRequest request, Integer id, String picture, 
			String bak1,String bak2,HttpServletResponse response) {
		if (picture != null && !picture.isEmpty()) {
			// RYWJSC
			String pathRoot = "";
			try {
				pathRoot = request.getSession().getServletContext().getRealPath("");
				//pathRoot = PropertiesUtil.getValue("pathRoot");
//				if (picture.startsWith("/resources")) {
//					new File(pathRoot + "/" + picture).delete();
//				} else {
//					new File(picture).delete();
//				}
//				String newPicture = picture.replace(PropertiesUtil.getValue("urlRoot"), "/");
				new File(pathRoot + picture).delete();
				
				if (bak1 !=null && !bak1.equals("")) {
//					String newBak1 = bak1.replace(PropertiesUtil.getValue("urlRoot"), "/");
					new File(pathRoot + bak1).delete();
				}
				
				if (bak2 !=null && !bak2.equals("")) {
//					String newBak2 = bak2.replace(PropertiesUtil.getValue("urlRoot"), "/");
					new File(pathRoot + bak2).delete();
				}
			} catch (Exception e) {
				return ServerResponse.createByError("删除失败，请确定目录文件是否存在 " + pathRoot + "/" + picture);
			}
		}
		if (!DEBUGMODE && !ValidateUtil.validateDel(PERMISSION)) {
			return ServerResponse.createByError("没有权限删除数据");
		}
		if (askLeaveService.hasCheck(id)) {
			return ServerResponse.createByError("已经审核过，无法再次修改");
		}
		askLeaveService.delAskLeave(id);
		return ServerResponse.createBySuccess();
	}

	@ResponseBody
	@RequestMapping("/testServletInterface")
	public Object testServletInterface(HttpServletRequest request, Integer id, String picture,
			HttpServletResponse response) {
		if (!DEBUGMODE && !ValidateUtil.validateQuery(PERMISSION)) {
			return ServerResponse.createByError("没有权限");
		}
		return ServerResponse.createBySuccess(request.getSession().getServletContext().getRealPath(""));
	}

	@RequestMapping("/editjsp")
	public String editjsp(HttpServletRequest request) {

		request.setAttribute("ConfigType", detailReadService.retrieveCategoryDetail(1027));
		request.setAttribute("User", userService.getAllEmploy());
		if (ValidateUtil.validateInput(PERMISSION)) {
			// request.setAttribute("User", userService.getAllEmploy());

			request.setAttribute("User", readService.listPerson());

			return "basedata/askleave/editAskLeaveInput";
		}
		return "basedata/askleave/editAskLeave";
	}
    
	//获得请假详情
	@RequestMapping("/getQinJiaDetail")
	public @ResponseBody List<AskLeave> getQinJiaDetail(Integer id){
		//根据主键查询到用户信息
		int personId = kaoqinService.selectPersonIdById(id);
		return  askLeaveService.selectPersonQinJiaByPersonId(personId);
	}
	
	@RequestMapping("add1")
	public @ResponseBody String add1() {
		return "xss";

	}

	@ResponseBody
	@RequestMapping("/add") // 增删改
	public Object add(HttpServletRequest request, AskLeave askLeave,
			@RequestParam(value = "file", required = false) MultipartFile file,
			@RequestParam(value = "file1", required = false) MultipartFile file1,
			@RequestParam(value = "file2", required = false) MultipartFile file2) {
		System.out.println("username=="+username);
		System.out.println("路径=="+request.getSession().getServletContext().getRealPath("a.txt"));
		if (!DEBUGMODE && !ValidateUtil.validateAdd(PERMISSION)) {
			return ServerResponse.createByError("没有权限添加数据");
		}

		if (askLeave.getStartTime() == null || askLeave.getEndTime() == null || askLeave.getDays() == null) {
			return ServerResponse.createByError("请假时间设置不完整");
		}

		if (!askLeave.getStartTime().before(askLeave.getEndTime())) {
			return ServerResponse.createByError("请假时间设置错误");
		}
		if (askLeave.getStartTime().getMonth() != askLeave.getEndTime().getMonth()) {
			return ServerResponse.createByError("不可以跨月申请");
		}

		if (askLeaveService.kaoQinMonthHasExist(askLeave.getStartTime().getYear() + 1900,
				askLeave.getStartTime().getMonth() + 1, ValidateUtil.validateUser().getId())) {
			return ServerResponse.createByError("请假的起始日期已经进行了月结结算");
		}
		if (askLeave.getDays().compareTo(
				new BigDecimal(askLeave.getEndTime().getDate() - askLeave.getStartTime().getDate() + 1)) > 0) {
			return ServerResponse.createByError("请假天数明显太长");
		}

		if (ValidateUtil.validateInput(PERMISSION)) {
			if (askLeave.getPersonId() == null || askLeave.getPersonId() == 0)
				return ServerResponse.createByError("没有选择人员");
			askLeave.setInput("1");
		} else {
			askLeave.setPersonId(ValidateUtil.validateUser().getId());
		}

		askLeave.getStartTime().setSeconds(0);
		askLeave.getEndTime().setSeconds(0);
		if (file != null && !file.isEmpty()) {
			// SCLD
			if (!file.getContentType().contains("image")) {
				return ServerResponse.createByError("请选择正确的图片");
			}
			String pathRoot = PropertiesUtil.getValue("urlRoot");
		    pathRoot = request.getSession().getServletContext().getRealPath(pathRoot);
			
			

			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			String path = uuid + file.getOriginalFilename();
			try {

				file.transferTo(new File(pathRoot + path));
			} catch (IllegalStateException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			askLeave.setPicture(path);
		}
		//上传第二张图片
		if (file1 != null && !file1.isEmpty()) {
			// SCLD
			if (!file1.getContentType().contains("image")) {
				return ServerResponse.createByError("请选择正确的图片");
			}
//			String pathRoot = request.getSession().getServletContext().getRealPath("");
			String pathRoot = PropertiesUtil.getValue("urlRoot");
			pathRoot = request.getSession().getServletContext().getRealPath(pathRoot);
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//			String path = "/resources/" + uuid + file1.getOriginalFilename();
			String path = uuid + file1.getOriginalFilename();
			try {

				file1.transferTo(new File(pathRoot  + path));
			} catch (IllegalStateException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
//			askLeave.setPicture(path);
			askLeave.setBak1(path);
		}
		
		//上传第三张图片
		if (file2 != null && !file2.isEmpty()) {
			// SCLD
			if (!file2.getContentType().contains("image")) {
				return ServerResponse.createByError("请选择正确的图片");
			}
//			String pathRoot = request.getSession().getServletContext().getRealPath("");
			String pathRoot = PropertiesUtil.getValue("urlRoot");
			pathRoot = request.getSession().getServletContext().getRealPath(pathRoot);
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//			String path = "/resources/" + uuid + file2.getOriginalFilename();
			String path = uuid + file2.getOriginalFilename();
			try {

				file2.transferTo(new File(pathRoot  + path));
			} catch (IllegalStateException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
//			askLeave.setPicture(path);
			askLeave.setBak2(path);
		}
		askLeave.setKjYear(askLeave.getStartTime().getYear() + 1900);
		askLeave.setPeriod(askLeave.getStartTime().getMonth() + 1);
		askLeave.setCheckerId(0);

		if (askLeaveService.addAskLeave(askLeave)) {
			return ServerResponse.createBySuccess("添加成功");
		}

		return ServerResponse.createByError("添加失败");

	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		DateFormat sdf_yyyyMMdd_hhmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		sdf_yyyyMMdd_hhmmss.setLenient(false);

		binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf_yyyyMMdd_hhmmss, true));
		binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, true));
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
		binder.registerCustomEditor(Long.class, new CustomNumberEditor(Long.class, true));
	}

	@ResponseBody
	@RequestMapping("/edit") // 增删改
	public Object edit(HttpServletRequest request, AskLeave askLeave,
			@RequestParam(value = "file", required = false) MultipartFile file) {

		System.out.println(request.getParameter("remark"));
		if (!DEBUGMODE && !ValidateUtil.validateEdit(PERMISSION)) {
			return ServerResponse.createByError("没有权限编辑数据");
		}

		if (askLeaveService.hasCheck(askLeave.getId())) {
			return ServerResponse.createByError("已经审核过，无法再次修改");
		}
		if (askLeave.getStartTime() == null || askLeave.getEndTime() == null || askLeave.getDays() == null) {
			return ServerResponse.createByError("请假时间设置不完整");
		}
		System.out.println(askLeave.getStartTime());

		if (!askLeave.getStartTime().before(askLeave.getEndTime())) {
			return ServerResponse.createByError("请假时间设置错误");
		}

		if (askLeave.getStartTime().getMonth() != askLeave.getEndTime().getMonth()) {
			return ServerResponse.createByError("不可以跨月申请");
		}

		if (askLeaveService.kaoQinMonthHasExist(askLeave.getStartTime().getYear() + 1900,
				askLeave.getStartTime().getMonth() + 1, ValidateUtil.validateUser().getId())) {
			return ServerResponse.createByError("请假的起始日期已经进行了月结结算");
		}

		if (askLeave.getDays().compareTo(
				new BigDecimal(askLeave.getEndTime().getDate() - askLeave.getStartTime().getDate() + 1)) > 0) {
			return ServerResponse.createByError("请假天数明显太长");
		}
		if (ValidateUtil.validateInput(PERMISSION)) {
			if (askLeave.getPersonId() == null || askLeave.getPersonId() == 0)
				return ServerResponse.createByError("没有选择人员");
			askLeave.setInput("1");
		} else {
			askLeave.setPersonId(ValidateUtil.validateUser().getId());
		}

		askLeave.getStartTime().setSeconds(0);
		askLeave.getEndTime().setSeconds(0);
		String pathRoot = request.getSession().getServletContext().getRealPath("");

		if (file != null && !file.isEmpty()) {

			if (!askLeave.getPicture().isEmpty()) {
				new File(pathRoot + "/" + askLeave.getPicture()).delete();
			}

			// SCLD
			if (!file.getContentType().contains("image")) {
				return ServerResponse.createByError("请选择正确的图片");
			}
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			String path = "/resources/" + uuid + "." + file.getOriginalFilename();
			try {
				file.transferTo(new File(pathRoot + "/" + path));
			} catch (IllegalStateException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			} catch (IOException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			askLeave.setPicture(path);
		}

		askLeave.setKjYear(askLeave.getStartTime().getYear());
		askLeave.setPeriod(askLeave.getStartTime().getMonth());

		if (askLeaveService.editAskLeave(askLeave)) {
			return ServerResponse.createBySuccess("更新成功");
		}

		return ServerResponse.createByError("更新失败");

	}
    
	@ResponseBody
	@RequestMapping("/recover") 
	public Object recover(int id) {
		try {
			askLeaveService.deleteApplyById(id);
			return ServerResponse.createByError("撤销成功");
		}
		catch (Exception e) {
			return ServerResponse.createByError("撤销失败"+e.getMessage());	
		}

		
	}
	
	
	@ResponseBody
	@RequestMapping("/check") // 增删改
	public Object check(AskLeave askLeave, Boolean isCheck, String type, String days, String years, String id,@RequestParam(name="isPhone",required=false)Boolean isPhone) {
        if(isPhone==null) {
        	if (!DEBUGMODE && !ValidateUtil.validateCheck(PERMISSION)) {
    			return ServerResponse.createByError("没有权限审批");
    		}
        }
		
		AskLeave ask = askLeaveService.askLeaveService(Integer.parseInt(id));
		if (isCheck) {
			askLeave.setCheckerId(ValidateUtil.validateUser().getId());
			askLeave.setCheckDate(new Date());
			// 更改数据
			Check check = new Check();
			Date date = ask.getStartTime();
			int year = date.getYear() + 1900;
			int month = date.getMonth() + 1;
			check.setDays(Float.parseFloat(days));
			int personId = ask.getPersonId();
			int realPersonId = personMapper.selectPersonIdByUserId(personId);
			check.setPersonId(realPersonId);
			check.setType(type);
			check.setYear(year);
			check.setMonth(month);
			String result = askLeaveService.updateKaoQin(check);
			if (result.equals("年假不足")) {
				return ServerResponse.createByError("年假不足");
			}
		} else {
			askLeave.setCheckerId(ValidateUtil.validateUser().getId());
			askLeave.setCheckDate(new Date());
			// 更改数据
			Check check = new Check();
			Date date = ask.getStartTime();
			int year = date.getYear() + 1900;
			int month = date.getMonth() + 1;
			check.setDays(Float.parseFloat(days));
			int personId = ask.getPersonId();
			int realPersonId = personMapper.selectPersonIdByUserId(personId);
			check.setPersonId(realPersonId);
			check.setType(type);
			check.setYear(year);
			check.setMonth(month);
			String result = askLeaveService.qishenKaoQin(check);

			askLeave.setCheckerId(0);
			askLeave.setCheckDate(null);

		}
		if (askLeaveService.editAskLeave(askLeave)) {
			return ServerResponse.createBySuccess("更新成功");
		}

		return ServerResponse.createByError("更新失败");
	}

	private ServletContext servletContext;
	private ServletConfig servletConfig = this;

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	@Override
	public void setServletConfig(ServletConfig servletConfig) {
		this.servletConfig = servletConfig;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public ServletConfig getServletConfig() {
		return this.servletConfig;
	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		// TODO Auto-generated method stub

	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return servletContext.getServerInfo();
	}

	@Override
	public void destroy() {
	}

	@Override
	public String getServletName() {
		// TODO Auto-generated method stub
		return "";
	}

	@Override
	public ServletContext getServletContext() {
		return this.servletContext;
	}

	@Override
	public String getInitParameter(String name) {
		// TODO Auto-generated method stub
		return "";
	}

	@Override
	public Enumeration<String> getInitParameterNames() {
		// TODO Auto-generated method stub
		return null;
	}

}
